<?php
/*
 * Yapp Session wrapper
 * Singleton class
 */

class yappSession
{
    private static $instance = false;
    private $sessionStarted  = false;
    private $sessionId       = false;
    private $sessionData     = array();
    private $keySeed         = "#00X_5e55i0n-SEED_X77#";

    private function __construct()
    {
        session_start();
        $this->sessionId = session_id();
        $this->sessionStarted = true;
        $this->sessionData = $_SESSION;
    }

    public static function getInstance()
    {
        if (!self::$instance)
        {
            self::$instance = new yappSession();
        }
        return self::$instance;
    }

    public function getId()
    {
        if (!$this->sessionStarted) return false;
        return $this->sessionId();
    }

    public function set($key, $data)
    {
        $key = $this->buildKey($key);
        if (!$this->sessionStarted) return false;
        $_SESSION[$key] = $data;
        $this->sessionData = $_SESSION;
        return true;
    }

    public function get($key)
    {
        if (!$this->sessionStarted) return false;
        $key = $this->buildKey($key);
        if (isset($this->sessionData[$key]))
        {
            return $this->sessionData[$key];
        }
        else
        {
            return false;
        }
    }

    public function writeClose()
    {
        if (!$this->sessionStarted) return false;
        session_write_close();
        $this->sessionStarted = false;
    }

    public function delete($key)
    {
        if (!$this->sessionStarted) return false;
        $key = $this->buildKey($key);
        if (isset($this->sessionData[$key]))
        {
            unset($_SESSION[$key]);
            $this->sessionData = $_SESSION;
        }
        else
        {
            return false;
        }
    }

    private function buildKey($key)
    {
        return sha1(md5($this->keySeed).'_'.$key);
    }

}
?>